﻿using ECMS.Infrastructure.Engines;
using ECMS.Manage.Authorizations;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using NLog.Extensions.Logging;
using NLog.Web;
using StructureMap;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.IO;
using System.Text;

namespace ECMS.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(opt => opt.EventsType = typeof(ECMSCookieAuthenticationEvents));
            services.AddScoped<ECMSCookieAuthenticationEvents>();

            //token验证
            var audienceConfig = Configuration.GetSection("Audience");
            //自定义密钥
            var symmetricKeyAsBase64 = audienceConfig["Secret"];
            //生成密钥
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(symmetricKeyAsBase64));

            var tokenValidationParameters = new TokenValidationParameters
            {
                SaveSigninToken = true,

                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = audienceConfig["Issuer"],

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = audienceConfig["Audience"],

                // Validate the token expiry
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                //不使用https
                //o.RequireHttpsMetadata = false;
                o.TokenValidationParameters = tokenValidationParameters;
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "ECMSManage API",
                    Description = "By fuchenyumu",
                    //TermsOfService = "None",
                    Contact = new Contact
                    {
                        Name = "@浮沉与木",
                        Email = "1184470032@qq.com",
                        Url = "http://www.fuchenyumu.com"
                    }
                    ,
                    //License = new License
                    //{
                    //    Name = "Use under LICX",
                    //    Url = "https://example.com/license"
                    //}
                });
                // Set the comments path for the Swagger JSON and UI.

                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录（绝对，不受工作目录影响，建议采用此方法获取路径）
                var xmlPath = Path.Combine(basePath, "ECMS.API.xml");

                options.IncludeXmlComments(xmlPath);
            });

            var connectionString = Configuration.GetConnectionString("ECMSConnection");
            //配置数据库上下文
            services.AddDbContext<Domain.ECMSDbContext>(opt => opt.UseSqlServer(connectionString, p => p.MigrationsAssembly("ECMS.Domain")));

            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //配置类
            services.AddSingleton<IConfiguration>(Configuration);
            //JSON首字母小写解决
            services.AddMvc().AddJsonOptions(options =>
            options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
            //添加session 
            services.AddSession();
            //添加跨域访问
            services.AddCors(options =>
            options.AddPolicy("AllowAnyOrigin",
                builder => builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));

            //注入服务
            BootStrapper.ECMSIocConfiguration.AddIocConfiguration(services);

            var container = new Container();

            container.Populate(services);

            EngineContainerFactory.InitializeEngineContainerFactory(new EngineContainer(container));

            return container.GetInstance<IServiceProvider>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory log)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseSession();//使用session

            app.UseStaticFiles();

            app.UseAuthentication();//添加认证中间件 
            
            app.UseCookiePolicy();

            log.AddNLog();

            env.ConfigureNLog("nlog.config");

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ECMSManage API V1");
                c.RoutePrefix = string.Empty;
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
